using System;
using System.Collections.Generic;
using System.Text;
using CMS.BIZ;
using AAM.DAL;
using AAM.BIZ;
using AAM.SQL;

namespace CMS.BOP
{
    public class SqlBizMessageProvider : SqlBizObjectProvider<BizMessage>
    {

        public static readonly string TableAlias = GetTableAlias();
        public static readonly string TableName =  GetTableName() + " " + TableAlias;
        public static readonly string AllRows = GetAllRows(TableAlias);

        public BizMessage Read(int messageId)
        {
            return Read(new ObjectID(BizMessage.ObjectType, new object[] {messageId}));
        }
        public List<BizMessage> ReadAllByMemberID(int memberId, int messageState, int? folderId)
        {

            Command command = null;
            if (folderId != null)
            {
                command = Connection.CreateCommand("SELECT " + AllRows + " FROM " + TableName + ", MessageStates msgSt " +
                "WHERE msgSt.MemberID=? AND msgSt.MessageFolder=? AND msgSt.MessageState=? AND " + TableAlias + ".MessageID=msgSt.MessageID");
                command.AddParameter(memberId);
                command.AddParameter(folderId);
                command.AddParameter(messageState);
            }
            else
            {
                command = Connection.CreateCommand("SELECT " + AllRows + " FROM " + TableName + ", MessageStates msgSt " +
                "WHERE msgSt.MemberID=? AND msgSt.MessageFolder IS NULL AND msgSt.MessageState=? AND " + TableAlias + ".MessageID=msgSt.MessageID");
                command.AddParameter(memberId);
                command.AddParameter(messageState);
            }
            DataReader reader = command.ExecuteReader();
            List<BizMessage> list = CreateListFromReader(reader);
            reader.Close();
            command.Dispose();
            return list;
        }
        public BizMessage ReadByMemberID(int messageId, int memberId)
        {

            Command command = Connection.CreateCommand("SELECT " + AllRows + " FROM " + TableName + ", MessageStates msgSt " +
            "WHERE msgSt.MessageID=? AND msgSt.MemberID=? AND " + TableAlias + ".MessageID=msgSt.MessageID");
            command.AddParameter(messageId);
            command.AddParameter(memberId);
            DataReader reader = command.ExecuteReader();
            BizMessage message = null;
            if(reader.Read()) message = CreateFromReader(reader);
            reader.Close();
            command.Dispose();
            return message;
        }
        public bool Delete(int messageId)
        {
            return Delete(new ObjectID(BizMessage.ObjectType, new object[] { messageId }));
        }
    }
}
